<template>

	<view>
		<map key='map' :show-location="true" :style="{'height':windowHeight+'px','width':windowWidth+'px'}"
			:latitude="latitude" :longitude="longitude" :markers='isReloadMap ? markers : []' @markertap="markertap"
			@poitap="poitap" :scale="16">
		</map>
		<view class="fixedbox">
			<view style="margin: 20upx; ">
				<u-search placeholder="输入搜索公司名字" v-model="name" @clear="clearSearch" @search="handleSearch"
					:clearabled="true" :showAction="false"></u-search>
			</view>
			<view class="uni-list">
				<view class="uni-list-cell">
					<view class="list-row">所属区县:</view>
					<view class="list-row select-box">
						<picker :custom-item="'暂不选择'" @change="bindPickerChangeCity" :value="indexCity" mode="region">
							<view class="uni-input">
								{{area||'- 省 - 市 - 区'}}
							</view>
						</picker>
					</view>
				</view>
				<view class="uni-list-cell">
					<view class="list-row">所属行业:</view>
					<view class="list-row select-box">
						<select-lay v-if="reload" @closeScroll="closeScroll" name="name" @inputClear="inputClear"
							@selectitem="selectitem"></select-lay>
					</view>
				</view>
			</view>
			<scroll-view style="height: 36vh;" :scroll-y="isOpenScroll">

				<view class="company-container">
					<view class="company-box" v-for="item in companyMapData" :key="item.id"
						@tap.stop="toCompany(item.id)">
						<!-- <u-form :model="company" labelWidth="80px" ref="uForm"> -->
						<view class="input-box">
							<text class="title">企业名称:</text>
							<text class="title2">{{item.name}}</text>
						</view>
						<view class="input-box">
							<text class="title">序<text style="visibility: hidden;">好好</text>号:</text>
							<text class="title2">{{item.id}}</text>


						</view>

						<view class="company-btns">
							<u-button color="#58b99d" shape="circle" size="small" text="查看报价"
								@tap.stop="toPrice(item.id)"></u-button>
							<u-button :color="item.status == 1&&item.quotation ==2?'#4579ef':'#979797'" shape="circle"
								size="small" text="签约" @tap.stop="handleLogout(item)"></u-button>
							<u-button color="#979797" shape="circle" size="small" text="上传资料"
								@tap.stop="toMes(item.id)">
							</u-button>
							<view class="icon">
								<image class="icon" src="@/static/index/green.png" mode="" @tap.stop="poi(item)">
								</image>
								<!-- <u-icon name="play-right" color="#2979ff" size="20" @tap.stop="poi(item)" class="icon">
								</u-icon> -->
							</view>
							<!-- <u-button color="#edc76c" shape="circle" size="small" text="报价方案"
								@tap.stop="toPdf(item.id)">
							</u-button> -->
						</view>
						<!-- </u-form> -->
					</view>
					<view class="" v-if="!k">
						<u-button color="#979797" shape="circle" size="small" text="获取更多" @tap.stop="getMore">
						</u-button>
					</view>
					<view class="" v-if="k">
						<u-button color="#979797" shape="circle" size="small" text="暂无">
						</u-button>
					</view>
					<view style="width: 100%; text-align: center; font-size: 28rpx; margin-top: 100rpx;">{{isText}}
					</view>
				</view>
			</scroll-view>
		</view>
		<u-modal :show="delShow" title="签约" content="是否签约？" close-on-click-overlay show-cancel-button @close="closeDel"
			@cancel="closeDel" @confirm="handleDel" />
	</view>
</template>

<script>
	import {
		customList,
		signing,
		customDetail
	} from "@/request/homeApi.js";
	import brl from "@/request/baseUrl.js"
	// import amap from "../../common/amap-wx.130.js";
	export default {
		data() {
			return {
				delShow: false,
				latitude: 30.65284,
				longitude: 104.066133,
				isText: '',
				markers: [],
				amapPlugin: null,
				mapInfo: [],
				id: 0, // 使用 marker点击事件 需要填写id
				area: "", //选择的地区
				index: 0,
				indexCity: [23, 1, 1],
				companyMapData: [],
				page: 1,
				last_page: 1,
				name: '',
				status: "nomore",
				cunstom_industry_id: '',
				isReloadMap: true,
				pdfUrl: '',
				reload: true,
				isOpenScroll: true,
				k: false,
				clo: true,
				inClear: true
			};
		},
		onLoad() {
			this.openConfirm()
		},
		onShow() {
			this.companyMapData = []
			this.area = ''
			this.name = ''
			this.page = 1
			this.cunstom_industry_id = ''
			this.reload = false
			this.$nextTick(() => {
				this.reload = true;
			})
			this.getLocationInfo()
			// this.getList()
		},
		computed: {
			windowHeight() {
				var systemInfo = uni.getSystemInfoSync();
				return systemInfo.windowHeight / 1.5;
			},
			windowWidth() {
				return uni.getSystemInfoSync().windowWidth;
			},
			loadingShow() {
				const {
					inClear,
					clo
				} = this;
				return {
					clo,
					inClear,
				};
			},
		},
		watch: {
			loadingShow: {
				handler(newValue) {
					if (!newValue.clo && !newValue.inClear) {
						this.companyMapData = []
						this.cunstom_industry_id = ''
						this.page = 1
						this.getList()
					}
				},
				deep: true,
				immediate: true,
			},
		},
		onPageScroll(e) {
			console.log(e.scrollTop);
			// if (e.scrollTop >= 92) {
			// 	......
			// }
		},
		// onReachBottom() {
		// 	console.log('我触底了')
		// 	let that = this
		// 	if (that.page < that.last_page) {
		// 		that.page = that.page + 1
		// 		that.getList()
		// 	}
		// },
		methods: {
			// 选择后触发的事件，item是选择的参数
			selectitem(index, item) {
				this.isOpenScroll = true
				this.page = 1;
				this.companyMapData = []
				this.cunstom_industry_id = item.id
				this.getList()
			},
			closeScroll(value) {
				this.clo = false
				if (value) {
					this.isOpenScroll = false
				} else {
					this.isOpenScroll = true
				}
			},
			inputClear(value) {
				this.inClear = value
			},

			// 关闭签约弹窗
			closeDel() {
				this.delShow = false;
			},
			// 打开签约弹窗
			handleLogout(item) {

				if (item.status == 1 && item.quotation == 2) {
					this.delShow = true;
					this.id = item.id
				}

			},
			WGS84ToGCJ(wgLon, wgLat) {
				var pi = 3.14159265358979324
				var ee = 0.00669342162296594323
				var a = 6378245.0

				var dLat = this.transformLat(wgLon - 105.0, wgLat - 35.0)
				var dLon = this.transformLon(wgLon - 105.0, wgLat - 35.0)
				let radLat = wgLat / 180.0 * pi;
				var magic = Math.sin(radLat);
				magic = 1 - ee * magic * magic;
				var sqrtMagic = Math.sqrt(magic);
				dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
				dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
				var mgLat = parseFloat(wgLat) + parseFloat(dLat);
				var mgLon = parseFloat(wgLon) + parseFloat(dLon);
				return {

					latitude: mgLat.toFixed(6),
					longitude: mgLon.toFixed(6),
				}
			},
			//转为纬度
			transformLat(x, y) {
				var pi = 3.14159265358979324;
				var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
				ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
				ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
				ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
				return ret
			},
			//转换经度
			transformLon(x, y) {
				var pi = 3.14159265358979324;
				var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
				ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
				ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
				ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
				return ret
			},
			// 签约
			handleDel() {
				this.delShow = false;

				signing({
					custom_lists_id: this.id
				}).then(res => {
					uni.showToast({
						title: res.msg,
						icon: "none",
					});
					if (res.code == 200) {
						if (res.msg == '不属于你的客户') {
							uni.showToast({
								title: res.msg,
								duration: 1500,
								icon: 'none',
							})
							return
						}
						uni.navigateTo({
							url: `/pages/bind/register?id=${this.id}`
						})
						this.companyMapData.forEach(item => {
							if (item.id == this.id) {
								item.status = 2
							}
						})
						this.delShow = false;
					}
				})
			},
			// 搜索
			handleSearch() {
				this.page = 1;
				this.companyMapData = []
				this.getList();

			},
			clearSearch() {
				this.name = ''
				this.companyMapData = []
				this.page = 1;
				this.getList();
			},
			// 客户详情
			toCompany(id) {
				uni.navigateTo({
					url: `/pages/home/company?id=${id}`
				})
			},
			// 查看报价
			toPrice(id) {
				uni.navigateTo({
					url: `/pages/home/bookList?id=${id}`
				})
			},
			// 上传资料
			toMes(id) {
				return
				uni.navigateTo({
					url: `/pages/bind/register?id=${id}`
				})
			},
			// 报价方案
			toPdf(id) {
				customDetail({
					id
				}).then(res => {
					if (res.code == 200) {
						let arr = res.data.quotation_detail ? res.data.quotation_detail : {}
						if (arr.files != '' && arr.files != null) {
							this.pdfUrl = brl.baseUrl + arr.files
							setTimeout(() => {
								uni.getSystemInfo({
									success: res => {
										// console.log(this.pdfUrl, 'this.pdfUrl');
										wx.downloadFile({
											url: this.pdfUrl,
											// filePath: wx.env.USER_DATA_PATH + '/1.pdf',
											success: function(res) {
												const filePath = res.tempFilePath;
												wx.openDocument({
													showMenu: true,
													filePath: filePath,
													success: function(
														res) {
														console.log(
															'打开文档成功'
														);
													}
												});
											}
										});
									}
								});
							}, 500)
						} else {
							uni.showToast({
								title: '暂无',
								duration: 1500,
								icon: 'none',
							})
						}
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1500,
							icon: 'none',
						})
					}
				})
			},
			// 客户列表
			getList() {
				let that = this
				that.markers = []
				if (that.area == '暂不选择暂不选择暂不选择') that.area = ""
				if (that.area != "" || that.name != "" || that.cunstom_industry_id != "") {
					that.longitude = ''
					that.latitude = ''
				}
				// console.log(that.latitude, that.longitude, 'dddddddddddddddddd')
				customList({
					page: that.page,
					name: that.name,
					address: that.area,
					entry_time: '',
					limit: 25,
					custom_industry_id: that.cunstom_industry_id,
					status: 1,
					lng: that.longitude,
					lat: that.latitude,
				}).then(res => {
					if (res.data.list.length === 0) {
						uni.showToast({
							title: '数据已全部获取完毕',
							icon: 'success',
							duration: 3000
						})
						that.k = true
						that.markers = that.companyMapData.map(item => {
							return {
								id: 1,
								latitude: parseFloat(that.latitude),
								longitude: parseFloat(that.longitude),
								title: item.name,
								iconPath: '/static/location.png',
								width: '25px',
								height: '25px',
							}
						})
						that.reloadMap()
						// console.log(that.markers,'that.markers')
						return
					}
					that.clo = true
					res.data.count == 0 ? that.isText = '暂无' : that.isText = ''
					res.data.count == 0 ? that.status = 'nomore' : that.status = ''

					that.companyMapData = that.companyMapData.concat(res.data.list)
					that.last_page = Math.ceil(res.data.count / res.data.list.length)
					// if (that.area && that.area.length > 0) {
					that.markers = that.companyMapData.map(item => {
						return {
							id: item.id,
							latitude: parseFloat(item.lat),
							longitude: parseFloat(item.lng),
							title: item.name,
							iconPath: '/static/location.png',
							width: '25px',
							height: '25px',
						}
					})
					// that.latitude = that.markers[0] ? that.markers[0].latitude : ''
					// that.longitude = that.markers[0] ? that.markers[0].longitude : ''
					that.reloadMap()
					console.log(that.markers, 'that.markers22')
					// }
				})
			},
			getMore() {
				this.page += 1
				this.getList()
			},
			poi(e) {
				console.log(e,'eeeeeeeee')
				const latitude = Number(e.lat)
				const longitude = Number(e.lng)
				const name = e.city
				uni.showModal({
					title: '提示',
					content: '确认前往' + name,
					success: (res) => {
						if (res.confirm) {
							uni.openLocation({
								latitude, // 目标位置的纬度
								longitude, // 目标位置的经度
								name, // 目标位置的名称
								// address: '目标位置地址',  // 目标位置的详细地址
								scale: 18 // 地图缩放级别，范围5-18，默认为18
							});
						}
					}
				});
			},
			poitap(e) {
				const latitude = e.detail.latitude
				const longitude = e.detail.longitude
				const name = e.detail.name
				uni.showModal({
					title: '提示',
					content: '确认前往' + name,
					success: (res) => {
						if (res.confirm) {
							// let t = this.companyMapData.filter(item => item.name == name )
							// console.log(t,'ttttttttt')
							// this.toCompany(id),
							uni.openLocation({
								latitude, // 目标位置的纬度
								longitude, // 目标位置的经度
								name, // 目标位置的名称
								// address: '目标位置地址',  // 目标位置的详细地址
								scale: 18 // 地图缩放级别，范围5-18，默认为18
							});
						}
					}
				});

			},
			markertap(e) {
				const markerId = e.markerId;
				const marker = this.markers.find(marker => marker.id === markerId);

				if (!markerId) return
				uni.showModal({
					title: '提示',
					// content: '确认前往' + marker.title,
					content: '确认查看' + marker.title + '详情',
					success: (res) => {
						if (res.confirm) {
							this.toCompany(markerId)
							// uni.openLocation({
							// 	latitude: marker.latitude, // 目标位置的纬度
							// 	longitude: marker.longitude, // 目标位置的经度
							// 	name: marker.title, // 目标位置的名称
							// 	// address: '目标位置地址',  // 目标位置的详细地址
							// 	scale: 18 // 地图缩放级别，范围5-18，默认为18
							// });
						}
					}
				});
				// console.log(marker)
			},
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value) //这里获取到选择的行业
				this.index = e.detail.value
				this.companyMapData = []
				this.getList();
			},
			bindPickerChangeCity(e) {
				let x = e.detail.value.indexOf('暂不选择', 0)
				if (x == 1) {
					e.detail.value.splice(x, 2)
				} else if (x == 2) {
					e.detail.value.splice(x, 1)
				}

				if (Array.isArray(e.detail.value) && e.detail.value.length > 0) {
					this.area = e.detail.value.join('') //从这里可以取到选择的区市
					this.companyMapData = []
					this.getList();

				}

			},
			reloadMap() {
				this.isReloadMap = false
				this.$nextTick(() => {
					this.isReloadMap = true
				})
			},
			// 获取地理位置
			getLocationInfo() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						const {
							latitude,
							longitude
						} = res; // 在这里的得到的经纬度

						let resDegree = this.WGS84ToGCJ(longitude, latitude)

						this.companyMapData = []
						this.area = ''
						this.name = ''
						this.page = 1
						this.cunstom_industry_id = ''

						this.latitude = resDegree.latitude
						this.longitude = resDegree.longitude
						this.getList()
						this.reloadMap()
					},
					fail: (err) => {
						console.log('locationErr', err)
						uni.showToast({
							title: '位置获取失败',
							icon: 'error',
							duration: 1000
						})
					}
				});
			},

			// 再次获取授权。当用户第一次拒绝后再次请求授权
			openConfirm() {
				if (this.latitude !== 30.65284 && this.longitude !== 104.066133) return
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					success: (res) => {
						if (res.confirm) {
							// uni.openSetting(); // 打开地图权限设置
							this.getLocationInfo()
						} else if (res.cancel) {
							uni.showToast({
								title: '你拒绝了授权，无法获得周边信息',
								icon: 'none',
								duration: 1000
							})
						}
					}
				});
			},


		},

	};
</script>

<style lang="scss" scoped>
	.flexRow {
		text-align: center;
		padding: 20upx;
		color: #a5a5a5;
		border-bottom: #a5a5a5 1px dotted;
		font-size: 20upx;
	}

	.fixedbox {
		position: fixed;
		left: 0;
		bottom: 0;
		background-color: #FFFFFF;
		padding: 0 10upx;
		border-top-left-radius: 20px;
		border-top-right-radius: 20px;
		width: 100vw;
		height: 60vh;
		box-sizing: border-box;
	}

	.company-container {
		.company-box {
			background-color: #f8f8f8;
			border-radius: 10upx;
			margin: 30upx 20upx;
			padding: 20rpx;
			font-size: 30upx;

			.input-box {
				display: flex;
				margin: 10rpx 0;

			}

			/deep/ .u-input {
				padding-top: 0 !important;
				padding-bottom: 0 !important;
			}

			.title {
				margin-right: 10px;
				color: #acacac;
				vertical-align: middle;
			}

			.title2 {
				color: #000;
				vertical-align: middle;
			}


		}
	}

	.company-btns {
		display: flex;
		margin-top: 20upx;

		/deep/ button {
			margin: 0 5px 0 0;
		}

		.icon {
			padding: 6rpx 24rpx;
			text-align: center;
			align-items: center;

			image {
				width: 44rpx !important;
				height: 32rpx !important;
			}
		}
	}


	.uni-list-cell {
		display: flex;
		margin: 10px;
		color: #acacac;
		align-items: center;

		.list-row {
			flex: 1;
			margin: 0 5px;
		}

		.select-box {
			min-width: 40upx;
			border-radius: 5upx;
			flex: 2.6;
		}

		.uni-input {
			background-color: #f2f2f2;
			padding: 10upx;
			position: relative;
			min-height: 50upx;
			line-height: 50upx;
			font-size: 30upx;

			&::after {
				content: '';
				width: 5px;
				height: 5px;
				position: absolute;
				right: 8px;
				top: 8px;
				border-right: solid 1px gray;
				border-bottom: solid 1px gray;
				transform: rotate(45deg);
			}

		}
	}
</style>